import React, { useState, useEffect, useRef } from 'react';
import Masonry from 'masonry-layout';  //实现瀑布流
import imagesloaded from 'imagesloaded'; //监听图片加载
import Waterfall from './components/ClientBooks';
import { Input, Space, Select, Row, Col } from 'antd';
import request from './request';
import { options } from './config';

let currentPage = 1;

function Client() {

    const [searchVal, setSearchVal] = useState();
    const [categoryVal, setCategoryVal] = useState();
    const [data, setData] = useState([]);
    const [hasMore] = useState(true);
    const [loading, setLoading] = useState(false);
    const containerRef = useRef();
    const startDateRef = useRef(null);

    const getBookList = (flag = false, category = categoryVal, search = searchVal) => {
        setLoading(true);
        request.get('/api/list', {
            params: { category, current: currentPage, name: search }
        }).then((response) => {
            const { list } = response;
            if (!list.length) {
                if (flag)   currentPage -= 1;
                else setData([]);
            } else {
                flag ? setData([...data, ...list]) : setData(list);
            }
        }).catch(() => {
            if (flag)   currentPage -= 1;
        }).finally(() => {
            setLoading(false);
        });
    };

    useEffect(() => {
        getBookList();
    }, []);

    useEffect(() => {
        currentPage = 1;
        getBookList(false, categoryVal, searchVal);
    }, [searchVal, categoryVal]);

    // 下拉加载
    const loadMoreData = () => {
        if (!startDateRef.current || Date.now() - startDateRef.current > 1000) {
            currentPage += 1;
            getBookList(true);
            startDateRef.current = Date.now();
        }
    };

    const advanceWidth = () => {
        if (containerRef.current) {
            new Masonry(containerRef.current, {
                itemSelector: '.imgBox', //要布局的网格元素
                columnWidth: '.imgBox', //自适应
                fitWidth: true, // 设置网格容器宽度等于网格宽度
                gutter: 20,
            });
        }
    };

    const imagesOnload = () => {
        const elLoad = imagesloaded('.pages_hoc')  //获取下拉加载里面的第一个盒子
        //always 图片已全部加载，或被确认加载失败
        elLoad.on('always', () => {
            // 调用瀑布流
            advanceWidth();
            setLoading(false);
        })
    };

    useEffect(() => {
        imagesOnload();
    }, [data]);


    const onSearch = (value) => {
        setSearchVal(value);
    };
    const handleSelectChange = (value) => {
        setCategoryVal(value);
    };

    return (
        <div className="page-container">

            <Row align="middle" className="filter-container" gutter={2}>
                <Col className="filter-select">
                    <Select
                        className="select"
                        allowClear
                        options={options}
                        // style={{width: 160}}
                        placeholder="类别"
                        onChange={handleSelectChange}
                    />
                </Col>
                <Col className="filter-search">
                    <Input.Search
                        className="search"
                        placeholder="搜索书名..."
                        enterButton="搜索"
                        onSearch={onSearch}
                        // style={{ width: 300  }}
                    />
                </Col>
                <Col className="page-tips">
                    <span style={{ color: '#fff', paddingLeft: '24px' }}>
                        注：本网站不支持在线交易，需线下获取
                        &nbsp;&nbsp;&nbsp;&nbsp;微信：15637822857
                        &nbsp;&nbsp;&nbsp;&nbsp;QQ：643360052
                        &nbsp;&nbsp;&nbsp;&nbsp;祝您生活愉快～
                    </span>
                </Col>

                <span className="mobile-tips" style={{ color: '#fff', paddingLeft: '24px' }}>
                    注：本网站不支持在线交易，需线下获取<br />
                    微信：15637822857&nbsp;&nbsp;
                    QQ：643360052
                </span>
            </Row>

            {/* <div className="filter-container">
                <Space size="large">
                    <Select
                        allowClear
                        options={options}
                        style={{width: 160}}
                        placeholder="类别"
                        onChange={handleSelectChange}
                    />

                    <Input.Search
                        placeholder="搜索书名..."
                        enterButton="搜索"
                        onSearch={onSearch}
                        style={{ width: 300  }}
                    />

                    <span style={{ color: '#fff', paddingLeft: '24px' }}>
                        注：本网站不支持在线交易，需线下获取
                        &nbsp;&nbsp;&nbsp;&nbsp;微信：15637822857
                        &nbsp;&nbsp;&nbsp;&nbsp;QQ：643360052
                        &nbsp;&nbsp;&nbsp;&nbsp;祝您生活愉快～
                    </span>
                </Space>
            </div> */}
            <Waterfall
                data={data}
                containerRef={containerRef}
                hasMore={hasMore}
                loading={loading}
                loadMoreData={loadMoreData}
            />
        </div>
    );
}

export default Client;
